//
//  XLNearbyViewController.m
//  XiangLove
//
//  Created by 李传坤 on 2018/8/27.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLNearbyViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "XLHTTPSessionManager.h"
#import "XLNearbyUserCell.h"
#import "XLAccountManager.h"
#import <ReactiveCocoa.h>
#import "XLMyFriendModel.h"
#import "XLPersonPageViewController.h"
#import "MJRefresh.h"
#import "BMHPromptView.h"
#import "XLAutoScrollView.h"
#import "XLWebViewController.h"
#import "XLTuijianBannnerListModel.h"
@interface XLNearbyViewController ()<CLLocationManagerDelegate,UITableViewDataSource,UITableViewDelegate>{
    float latitude;
    float longitude;
    NSString *city;
}
@property (nonatomic,strong) UITableView    *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,copy  ) NSString            *page;
@property (nonatomic,strong) XLMyFriendModel   *FriendModel;
@property (nonatomic,strong) UIButton       *charmBtn;
@property (nonatomic, strong) BMHPromptView      *promptView;
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSString *fileType;

//记录滑动
@property (nonatomic, assign) float contentOffset;
@property (nonatomic, assign) float oldOffset;
@end

@implementation XLNearbyViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _page = @"1";
    if ([XLAccountManager shareInstance].model.Sex == 1) {
        _fileType = @"0";
    }else{
        _fileType = @"1";
    }
    self.fd_prefersNavigationBarHidden = YES;
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self addTableView];
    
    city = [kUserDefaults objectForKey:KUserNowCity];
    if (city.length > 0) {
        latitude = [[kUserDefaults objectForKey:KUserNowLatitude] floatValue];
        longitude = [[kUserDefaults objectForKey:KUserNowLongitude] floatValue];
        [self requrstTalkedPeoplePage];
    }else
    {
        [self getLocation];
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeSelectInfor:) name:@"changeSelectInfor" object:nil];;
    // Do any additional setup after loading the view.
}

#pragma mark ---获取位置 （当userdefault中的位置为空的时候才去获取 否则直接用存储的地址来获取数据）
-(void)getLocation
{
    //初始化定位管理器
    self.locationManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locationManager.delegate = self;
    //定位精准度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    //横向移动多少距离后更新位置信息
    self.locationManager.distanceFilter = 1000;
    //ios8以后需要获取定位权限
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }
    [self dingwei];
}

- (void)dingwei{//判断定位是否开启
    if ([CLLocationManager locationServicesEnabled]){//  判断用户是否允许程序获取位置权限
        if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse||[CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedAlways){
            //用户允许获取位置权限//开始定位
            [self.locationManager startUpdatingLocation];
        }else{
            //用户拒绝开启用户权限
            [self.locationManager startUpdatingLocation];
            self.promptView.hidden = NO;
        }
    }else{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"开启定位服务" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启),才能看到附近的人" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击取消");
        }]];

        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            NSLog(@"点击确认");
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }

}
-(void)changeSelectInfor:(NSNotification *)notification
{
    _page = @"1";
    if (![notification.userInfo[@"key"] isKindOfClass:[NSString class]]) {
        NSInteger loadPathStr = [notification.userInfo[@"key"] integerValue];
        if (loadPathStr == 101) {
            _fileType = @"1";
        }else if (loadPathStr == 102){
            _fileType = @"0";
        }else if (loadPathStr == 103){
            _fileType = @"-1";
        }
    }
    [self requrstTalkedPeoplePage];
}
#pragma mark - getter
- (BMHPromptView *)promptView {
    if (_promptView == nil) {
        _promptView = [[BMHPromptView alloc] initWithImage:[UIImage imageNamed:@"pic_nothing_n"]];
        [_promptView.reTryButton setTitle:@"点击开启定位" forState:UIControlStateNormal];
        _promptView.reTryButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_promptView.reTryButton setTitleColor:kRedColor forState:UIControlStateNormal];
        @weakify(self);
        _promptView.touchBlock = ^{
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"开启定位服务" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启),才能看到附近的人" preferredStyle:UIAlertControllerStyleAlert];
            
            [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击取消");
                
            }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                //跳转到定位开关界面
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                NSLog(@"点击确认");
                
            }]];
            @strongify(self)
            [self presentViewController:alertController animated:YES completion:nil];
        };
        [self.view addSubview:_promptView];
        [_promptView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(200, 215));
            make.center.equalTo(self.view);
        }];
    }
    return _promptView;
}

-(void)requrstTalkedPeoplePage{
    if (city == nil) {
        [self dingwei];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    NSDictionary *dic = @{@"pageIndex":_page,
                          @"pageSize":@"16",
                          @"userId":[[XLAccountManager shareInstance]model].Id,
                          @"fileter":_fileType,
                          @"logitude":[NSString stringWithFormat:@"%f",longitude],
                          @"latitude":[NSString  stringWithFormat:@"%f",latitude],
                          @"city":city
                          };
    [[[XLHTTPSessionManager sharedManager]XLV2GET:@"/Api/v2/UserInfo/SearchNearlyUser" parameters:dic resultClass:[XLMyFriendModel class]] subscribeNext:^(id x) {
        NSLog(@"美女列表==%@",x);
        [MBProgressHUD hideHUDForView:self.view];
        self.tableView.hidden = NO;
        
        NSArray * listAry = x;
        if (![x isKindOfClass:[NSNull class]] && listAry.count > 0) {
            [_promptView removeFromSuperview];
            _promptView = nil;
            [self getJsonArray:listAry];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }else{
            if ([self.page isEqualToString:@"1"]) {
                self.promptView.hidden = NO;
                self.tableView.hidden = YES;
            }
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } error:^(NSError *error) {
        NSLog(@"%@", error);
        if ([self.page isEqualToString:@"1"]) {
            self.promptView.hidden = NO;
            self.tableView.hidden = YES;
        }
        [MBProgressHUD hideHUDForView:self.view];
        if (self.modelArray.count == 0) {
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
    
}

- (void)getJsonArray:(NSArray *)array {
    if ([array isKindOfClass:[NSNull class]] || array.count == 0 || array == nil) {
        
    } else {
        if ([self.page isEqualToString:@"1"]) {
            [self.modelArray removeAllObjects];
        } else {
            
        }
        [self.modelArray addObjectsFromArray:array];
    }
    [self.tableView reloadData];
}
#pragma mark - 下拉刷新
- (void)handelGCHeaderTableView {
    self.page = @"1";
    [self requrstTalkedPeoplePage];
    //[self reshOnlinePeoplesData];
    
}

#pragma mark - 上拉加载
- (void)handelGCFootTableView {
    self.page = [NSString stringWithFormat:@"%d", [self.page intValue] + 1];
    [self requrstTalkedPeoplePage];
}

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(void)addTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, XQScreenW, XQScreenH - 49) style:UITableViewStylePlain];
    _tableView.rowHeight = 86;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    [_tableView registerClass:[XLNearbyUserCell class] forCellReuseIdentifier:NSStringFromClass([XLNearbyUserCell class])];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(handelGCHeaderTableView)];
    header.stateLabel.hidden = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    _tableView.mj_header = header;
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(handelGCFootTableView)];
    [self.view addSubview:_tableView];
}

#pragma mark ---tableview 代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 10)];
    headView.backgroundColor = RGB_HEX(0xf6f6f6);
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 104;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLNearbyUserCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLNearbyUserCell class]) forIndexPath:indexPath];
    XLMyFriendModel  *model = [self.modelArray objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.headerImageView setImageWithURL:[NSURL URLWithString:model.HeadImg] placeholder:[UIImage imageWithColor:RGB(255, 255, 255)]];
    NSString *levelUrl;
    if ([model.IsAnchor integerValue] == 1) {
        levelUrl = [NSString stringWithFormat:@"me_grade_icons_zb0%@",model.UserLevel];
    }else{
        levelUrl = [NSString stringWithFormat:@"me_grade_icons_yh0%@",model.UserLevel];
    }
    if ([model.UserLevel integerValue] > 9) {
        if ([model.IsAnchor integerValue] == 1) {
            levelUrl = [NSString stringWithFormat:@"me_grade_icons_zb%@",model.UserLevel];
        }else{
            levelUrl = [NSString stringWithFormat:@"me_grade_icons_yh%@",model.UserLevel];
        }
    }
    cell.nickNameLabel.text = model.NickName;
    if (cell.nickNameLabel.text.length == 0) {
        cell.nickNameLabel.text = @"      ";
    }
    CGFloat width = 91;//加上头像
    cell.ageLabel.frame = CGRectMake(width, 45, 30, 16);
    cell.sexImage.frame = CGRectMake(width + 4, 49, 8, 8);
    cell.nvshenLabel.frame = CGRectMake(width + 36, 45, 38, 16);
    cell.nvshenImage.frame = CGRectMake(width + 39, 48, 9, 9);
    if ([model.Sex integerValue] == 1) {
        cell.ageLabel.backgroundColor = RGB_HEX(0xFFA6D8);
        cell.sexImage.image = [UIImage imageNamed:@"common_icon_nv_n"];
        if ([model.IsAnchord integerValue] == 1) {
            cell.nvshenLabel.backgroundColor = RGB_HEX(0xFF6699);
            cell.nvshenImage.image = [UIImage imageNamed:@"common_icon_rzns_n"];
            cell.nvshenLabel.text = @"     女神";
            cell.nvshenLabel.hidden = NO;
            cell.nvshenImage.hidden = NO;
        }else{
            cell.nvshenLabel.hidden = YES;
            cell.nvshenImage.hidden = YES;
        }
    }else
    {
        cell.ageLabel.backgroundColor = RGB_HEX(0xB7D0FF);
        cell.sexImage.image = [UIImage imageNamed:@"common_icon_nan_n"];
        if ([model.IsAnchord integerValue] == 1) {
            cell.nvshenLabel.backgroundColor = RGB_HEX(0x45B8F9);
            cell.nvshenImage.image = [UIImage imageNamed:@"common_icon_rzns_n"];
            cell.nvshenLabel.text = @"     男神";
            cell.nvshenLabel.hidden = NO;
            cell.nvshenImage.hidden = NO;
        }else{
            cell.nvshenLabel.hidden = YES;
            cell.nvshenImage.hidden = YES;
        }
    }
    cell.locationState.text = [NSString stringWithFormat:@"%@ ·",model.DisplayCurrent];
    cell.ageLabel.text = [NSString stringWithFormat:@"     %@",model.Age];
    cell.infor.text = model.Info;
    
    if ([model.OnlineStatus isEqualToString:@"0"]) {
        cell.onlineState.text = @"离线";
        
    }else{
        
        cell.onlineState.text = @"在线";
    }
    
    return  cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    XLMyFriendModel *model = self.modelArray[indexPath.row];
    //跳转私聊界面
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {//
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[NSStringFormat(@"%@",model.UserId)] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    //                    chat.isAnchor = model[@"IsAnchor"];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            NSLog(@"msg");
        }];
        return;
    }
    XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
    vc.userId = model.UserId;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark ----判断tableview上滑还是下滑
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    self.contentOffset = scrollView.contentOffset.y;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat newOffsetY = scrollView.contentOffset.y;
    if (newOffsetY > self.oldOffset && self.oldOffset > self.contentOffset){//上滑
        //写上滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(NO);
        }
    }else if(newOffsetY < self.oldOffset && self.oldOffset < self.contentOffset){//下滑
        //写下滑代码
        if(self.slideDistanceBlock)
        {
            self.slideDistanceBlock(YES);
        }
    }
    self.oldOffset = scrollView.contentOffset.y;
}
//记录滑动结束时候的offset
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    self.oldOffset = scrollView.contentOffset.y;
}


#pragma mark - CLLocationManagerDelegate
// 地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // 获取经纬度
    NSLog(@"纬度:%f",newLocation.coordinate.latitude);
    NSLog(@"经度:%f",newLocation.coordinate.longitude);
    // 停止位置更新
    [manager stopUpdatingLocation];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //当前所在城市的坐标值
    CLLocation *currLocation = [locations lastObject];
    NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
    //根据经纬度反向地理编译出地址信息
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        for (CLPlacemark * placemark in placemarks) {
            NSDictionary *address = [placemark addressDictionary];
            //  Country(国家)  State(省)  City（市）
            NSLog(@"#####%@",address);
            NSLog(@"%@", [address objectForKey:@"Country"]);
            NSLog(@"%@", [address objectForKey:@"State"]);
            NSLog(@"%@", [address objectForKey:@"City"]);
            city =  [address objectForKey:@"City"];
            latitude = currLocation.coordinate.latitude;
            longitude = currLocation.coordinate.longitude;
            if (city.length > 0) {
                [manager stopUpdatingLocation];
                [self requrstTalkedPeoplePage];
            }
        }
    }];
    
}
// 定位失误时触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"error:%@",error);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
